<?php
class System_Model_DimensionMapper {
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('System_Model_DbTable_Dimension');
		}
		return $this->_dbTable;
	}
	public function save(System_Model_Dimension $dimension){
		try{
			$result=$this->getDbTable()->insert($dimension->toArray());
		}catch (Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		return (int)$result;
	}
	public function update(System_Model_Dimension $dimension){
		try{
			$result=$this->getDbTable()->update($dimension->toArray(), $this->getDbTable()->getAdapter()->quoteInto('id = ?', $dimension->getId()));
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		return (int)$result;
	}
	public function findAll($perPage=10,$curPage=1,$gid,$to_json=true){
		$select=$this->getDbTable()->select()->from("dimension")->order("id")->where("gid=".$gid)
		->limitPage($curPage, $perPage);
		$rows=$this->getDbTable()->getAdapter()->fetchOne("select count(*) from dimension where gid=".$gid);
		$data=array();
		try{
			$data=$this->getDbTable()->fetchAll($select)->toArray();
		}catch (Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		$response=new stdClass();
		$response->page=$curPage;
		$response->total=ceil($rows/$perPage);
		$response->records=(int)$rows;
		$response->rows=$data;
		$response->gid=$gid;
		if($to_json){
			return json_encode($response);
		}else{
			return $response;
		}
	}
	
	public function findAllList($gid){
		try{
			$result=$this->getDbTable()->fetchAll("gid=".$gid)->toArray();
		}catch (Exception $e){
			return $e;
		}
		return $result;
	}
	
	public function findById($id,System_Model_Dimension $dimension){
		try{
			$result=$this->getDbTable()->find($id);
		}catch(Exception $e){
			return $e;
		}
		if(count($result)==0){
			return "没有找到ID记录号为".$id."的维度信息";
		}
		$dimension->setOptions($result->current()->toArray());
	}
	
	public function deleteAll($gid){
		try{
			$this->getDbTable()->delete("gid=".$gid);
		}catch(Exception $e){
			return $e;
		}
	}
	
	
}
